from fastapi import FastAPI
from pydantic import BaseModel,constr
from typing import Optional
import uvicorn

app = FastAPI()


class City(BaseModel):
    id: int
    name:constr(max_length=50) # 可以通过 constr 限制字符串长度
    infectors: int

db = {
    "10": City(id=10,name="北京",infectors=200),
    "33": City(id=33,name="浙江",infectors=120),
    "65": City(id=65,name="新疆",infectors=20),
    "44": City(id=44,name="广东",infectors=300),
}

@app.get("/")
async def index():
    return "welcome to here"

#1、路径参数
@app.get("/city/{city_id}")
async def get_city(city_id:int):
    id = str(city_id)
    if id in db:
        return db[id].json()
    else:
        return None

#/city?id=33&name=上海
#2、查询参数
@app.get("/city")
async def find_city(name:str,id:int=None):
    return {
        "id":id,
        "name":name
    }

#3、路径参数和查询参数
@app.get("/citys/{id}")
async def find_city_q(id:int,name:str=None):
    return {
        "id":id,
        "name":name
    }

#4、Body 中 的数据提交
@app.put("/city/{id}")
async def update_city(id:int,city:City):
    print(city)
    return city.json()

if __name__ == "__main__":
    uvicorn.run("04_fastapi_请求参数:app",reload=True)
